package cn.com.generaldata.os.service.indicator_evaluation.coefficient_of_variation;

import java.util.List;

import org.apache.commons.lang3.Validate;

import cn.com.generaldata.jsme_indicator_system.entity.IndicatorEvaluation;
import cn.com.generaldata.jsme_indicator_system.util.Constants;
import cn.com.generaldata.os.service.indicator_constant.ProvinceIndicatorConstant;
import cn.com.generaldata.os.service.indicator_evaluation.IndicatorEvaluationCalculateService;
import cn.com.generaldata.os.util.BeanMapper;
import cn.com.generaldata.os.vo.IndicatorAccountVO;

import com.google.common.collect.Lists;

/**
 * GOP变异系数评估指标计算类.
 */
public class GOPVariableCoefficientCalculateService extends IndicatorEvaluationCalculateService {

	private String GOPIndicatorName = ProvinceIndicatorConstant.GOP_INDICATOR_NAME;

	@Override
	protected Double calculate(IndicatorEvaluation indicator, IndicatorAccountVO indicatorAccountVO) {
		Double result = null;
		if (indicator.getSection() == Constants.INDICATOR_LEVEL_PROVINCE) {
			result = calculateProvinceResult(indicator, indicatorAccountVO);
		} else if (indicator.getSection() == Constants.INDICATOR_LEVEL_CITY) {
			// 先保留
		}
		return result;

	}

	private Double calculateProvinceResult(IndicatorEvaluation indicator, IndicatorAccountVO indicatorAccountVO) {
		Double cityGOPSum = 0d;
		List<Double> cityGOPS = Lists.newArrayList();
		for (String areaId : ProvinceIndicatorConstant.CITYS) {
			IndicatorAccountVO vo = BeanMapper.map(indicatorAccountVO, IndicatorAccountVO.class);
			vo.setAreaId(areaId);
			Double gop = getCityGOP(vo);
			cityGOPSum += gop;
			cityGOPS.add(gop);
		}

		Double avgGOP = cityGOPSum / ProvinceIndicatorConstant.CITYS.length;

		Double d = 0d;
		for (Double gop : cityGOPS) {
			d += Math.pow((gop - avgGOP), 2);
		}
		return Math.pow(d / ProvinceIndicatorConstant.CITYS.length, 0.5) / avgGOP;
	}

	private Double getCityGOP(IndicatorAccountVO indicatorAccountVO) {
		Double gop = getInputOrAccountingIndicatorValue(indicatorAccountVO, indicatorAccountVO.getYear(),
				GOPIndicatorName);
		Validate.isTrue(gop != null);
		return gop;
	}

}
